from werkzeug.security import generate_password_hash,check_password_hash
from flask import Blueprint,request,jsonify
import database
import json
import re
import random
from utils.redisconn import r
from utils.comm import send_message
from views.jwt_token import myjwt

from conf.comm import sqlalchemy_context
from database import *
#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST','GET','PUT','DELETE'])
@sqlalchemy_context()
def reg():
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(request.data)
    mobile = data['mobile']
    if not re.match('^1[3-9]\d{9}$', mobile):
        return jsonify({"code":11111})
    try:
        if request.method == 'POST':
            u = User(username=data['username'],password=generate_password_hash(data['password']),mobile=data['mobile'])
            db.session.add(u)
            db.session.commit()
            return jsonify({"code":200})
    except:
        return jsonify({"code":10010})


@bp_users.route('/sendsms',methods=['POST'])
def sendsms():
    # 获取传递手机号
    data = json.loads(request.data)
    mobile = data['mobile']
    if not mobile:
        return jsonify({'code': 20010, 'mes': '必须输入手机号'})
    # 用手机号去redis中取验证码，如果能取到返回，请30秒后发
    v = r.get_str(mobile)
    if v:
        return jsonify({"code": 20021, 'mes': '请1分钟后发'})
        # 生成验证码
    code = str(random.randint(100000, 999999))
    # 调用短信接口
    flag = send_message(mobile, code, 1)
    if flag:
        # 发送成功，存入redis
        r.set_str(mobile, code, 60)
        # 返回结果（验证码）
        return jsonify({'code': 200, 'smscode': code})
    else:
        return jsonify({'code': 20011, 'mes': '发送失败，请重试'})

@bp_users.route('/mlogin',methods=['POST'])
def mlogin():
    data = json.loads(request.data)
    mobile = data['mobile']
    code = data['code']
    if not re.match('^1[3-9]\d{9}$', mobile):
        return jsonify({"code":10010,'meg':"手机号错误"})
    if not code:
        return jsonify({"code": 10010, 'meg': "验证码不能为空"})
    user = database.User.query.filter_by(mobile=mobile).first()
    if r.get_str(mobile) == str(code):
        token = myjwt.encode_jwt({'id':user.id})
        return jsonify({"code":200,'token':token})



@bp_users.route('/login',methods=['POST'])
def login():
    data = json.loads(request.data)
    username = data['username']
    password = data['password']
    user = database.User.query.filter_by(username=username).first()
    if user:
        if check_password_hash(user.password,password):
            token = myjwt.encode_jwt({'id':user.id})
            return jsonify({"code":200,'token':token})
        else:
            return jsonify({"code":10010,'meg':'密码错误'})
    return jsonify({"code":10010,'meg':'用户名不存在'})

